package com.dns.customers.service.impl;

import com.dns.customers.dao.CustomerDao;
import com.dns.customers.service.LoginService;
import com.util.DesUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
public class LoginServiceImpl implements LoginService{

    @Autowired
    CustomerDao customerDao;

    /**
     * 用户登录
     * @param req
     * @param res
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(HttpServletRequest req, HttpServletResponse res, String username, String password) {
        JSONObject result = new JSONObject();
        try{
            if(username == null || "".equals(username)){
                result.put("errorMsg","请输入账号！");
                result.put("errorCode","1111");
                return result.toString();
            }
            if (password == null || "".equals(password)){
                result.put("errorMsg","请输入密码！");
                result.put("errorCode","1112");
                return result.toString();
            }
            Map<String,Object> user =  customerDao.queryUserById(username);
            if (user == null){
                result.put("errorMsg","没有这个账户！");
                result.put("errorCode","1113");
                return result.toString();
            }
            String pass = user.get("CUST_PASSWORD")+"";
            if (DesUtil.encrypt(password).equals(pass)){
                HttpSession session = req.getSession();
                session.setAttribute("user",user);
                session.setAttribute("userId",username);
                result.put("errorMsg","登录成功！");
            }else {
                result.put("errorMsg","密码错误！");
                result.put("errorCode","1113");
                return result.toString();
            }
        }catch (Exception e){
            result.put("errorMsg","登录异常！");
            result.put("errorCode",e.getMessage());
            return result.toString();
        }
        return result.toString();
    }
}
